<?php
class Order_Service_DispatchProccess
{
	protected $_order = null;	 
	protected $_orderCode = null;
	protected $_customerId = null;
	protected $_outOfBalance = false;
	protected $_error = null;
	protected $_customer = null;
	protected $_weight = null;
	protected $_length =null;
	protected $_width  =null;
	protected $_height  =null;
	protected $_shipFee = null;
	protected $_shipFeeCurrencyCode = 'RMB';//货运币种
	protected $_currency_rate=null;  //当前币种的汇率
	protected $_status = null;
	protected $_tracking_number=null;  //物流单号
	public    $_result=false;
	public    $_isWeight=true;
	public    $_ignoreWeight=false;
	public    $_shippingMethod=null;
	public    $_volWeight=false;
	protected $_shipType = null;
	public    $_volWeightRate=null;

	public function __construct($array){
        if($array!=null){
			foreach($array as $key=>$val){
				$this->set('_'.$key,$val);
			}
		}
		$this->setOrder();
		$this->checkShipType();
	}
    private function set($key,$value){
		$this->$key =$value;
	}
	
	/*
	*判断是否扣物流费用
	*return true=>不扣费, false=>正常扣费
	*/
	 private function getCheckFee(){
		if($this->_order['shipping_method']=='SELFPICKUP'){
			return true;
		}
		return false;
	 }
	
	public function DispatchTransaction(){
		$customerBalance = new Customer_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getAdapter();
		$dbAdapter->beginTransaction(); 
		try{
			if(!$this->checkOrder()){
				return false;
			}
			//如果是不忽略重量
			if(!$this->_ignoreWeight){
				if(!$this->checkWeight()){
					return false;
				}
			}
			
			//运输方式为自提,不涉及运费
			if(!$this->getCheckFee()){
			    
				$this->shippingFee();
				
				if($this->_outOfBalance==true){
					$dbAdapter->rollback();
					return false;
				}
				if(!$this->release()){
					$dbAdapter->rollback();
					return false;
				}
				if(!$this->procBalance()){
					$dbAdapter->rollback();
					return false;
				}

				//修改物流单
				if(!$this->boundOrder()){
					$dbAdapter->rollback();
					return false;
				}
			}
			//修改库存冻结
			if(!$this->updateQuantityHold()){
				$dbAdapter->rollback();
				return false;
			}
			
			
			if(!$this->updateOrderHistory()){
				$dbAdapter->rollback();
				return false;
			}
			
			//修改状态(订单表两个状态字段，都改成已出货状态)
			if(!$this->updateOrderStatus()){
				$dbAdapter->rollback();
				return false;
			}
			
			
			$dbAdapter->commit();
			return true;
		}catch(Exception $e){
			$this->_error[]=$e->getMessage();
	    	$dbAdapter->rollback();
	    	return false;
	    }
	}
	 private function setOrder(){
	 	$lang = Zend_Registry::get('lang');
		if(!isset($this->_order)||$this->_order['orders_code']==$this->_orderCode ){
			$this->_order = current(Order_Service_Order::getByfield('orders_code',$this->_orderCode));
			$this->_customerId=$this->_order['customer_id'];
			$this->_shippingMethod=$this->_order['shipping_method'];
		}
	 }
	 //检查订单状态
	 private function checkOrder(){
		 $lang = Zend_Registry::get('lang');
		if($this->_order['process_status']!=4){
			$this->_error[]=$lang['order_status_wrong_can_not_ship'];
			//$this->_outOfBalance=True;
			return false;
		}
		switch ($this->_order['underreview_status']){
			case 3:
				$this->_error[]=$lang['order_stop_can_not_ship'];
				return false;
				break;
			case 2:
				$this->_error[]=$lang['order_balance_insufficient_can_not_ship'];
				return false;
				break;
			case 1:
				$this->_error[]=$lang['order_inventory_insufficient_can_not_ship'];
				return false;
				break;
					
		}
		
		return true;
	 }
	 
	 //检查订单物流方式对应的类型
	 public function checkShipType(){
	 	$shipMethod = Shipping_Service_ShipType::getByValue($this->_order['shipping_method'],'st_code');
	 	if($shipMethod){
	 		$st_vol_weight_rate=$shipMethod['st_vol_weight_rate'];
	 		if($st_vol_weight_rate>0){
	 			$this->_volWeight=true;
	 		}
	 	}
	 	
	 	
	 }

	 private function setWeight(){
		if( !isset($this->_weight) &&(!isset($this->_order)||$this->_order['orders_code']==$this->_orderCode )){
			$this->_weight=0;
		}
	 }
	 /*
	 *
	 *Return Order Info
	 */
	 public function getOrder(){
		 return $this->_order;
	 }

	 public function getError(){
		 return $this->_error;
	 } 
	 
	 public function getshippingMethod(){
	 	return $this->_shippingMethod;
	 }
	 
	 public function getshipType(){
	 	return $this->_volWeight;
	 }
	 
	 
	 /**
	 *计算运费
	 */
	private function shippingFee(){
	    $lang = Zend_Registry::get('lang');
		$this->setWeight();
		$shipMethod = Shipping_Service_ShipType::getByValue($this->_order['shipping_method'],'st_code');
		$options = array('warehouseId'=>$this->_order['warehouse_id'],
						'countryId'=>$this->_order['consignee_country_id'],
						'stId'=>$shipMethod['st_id'],
						'weight'=>$this->_weight,
						'length'=>$this->_length,
						'width'=>$this->_width,
						'height'=>$this->_height,
						'customerId'=>$this->_customerId,
						);
		$shipFeeObj = new Shipping_Service_ShipFeeCalc($options);		
		$fee = $shipFeeObj->calcFeeByType();
		if(!isset($fee['inter_fee'])){
			$this->_outOfBalance = true;
			$this->_error[]=$lang['get_ship_fee_fail'].$fee;
		}
		$this->_shipFeeCurrencyCode = $fee['currency_code'];//币种
		$this->_shipFee = $fee['inter_fee'];
		$this->_shipType = $fee;
	 }
	 
	/*
	*获取当前币种的汇率
	*/
	private function setCurrencyRate(){
		$Row = Common_Service_Currency::getByCode($this->_shipFeeCurrencyCode);
		if($Row){
			$this->_currency_rate=$Row['currency_rate'];
		}
	}
	
	//获取体积转换率
	public function getvolWeightRate(){
		$shipType=array();
		$this->_volWeightRate=0;
		if($this->_shippingMethod){
			$shipType=Shipping_Service_ShipType::getAllByValue($this->_order['shipping_method'],'st_code');
			if($shipType){
				$this->_volWeightRate=$shipType[0]['st_vol_weight_rate'];
			}
		}
		
		return $this->_volWeightRate;
	}
	 
	 /**
	 *获取运费
	 */
	 public function getShippingFee(){
		$this->shippingFee();
		return $this->_shipFee;
	 } 
	 
	/*
	*release balance Value 解冻
	*/
	private function release(){
		$result=Customer_Service_CustomerBalance::release($this->_customerId,$this->_order['orders_code'],3);
		if($result['ask'] == "Success"){
			return true;
		}
		$this->_error[] = $result['message'];
		return false;
	}
	 /*
	 *release()解冻后，再扣费用
	 */
	 private function procBalance(){ 	
		$note = 'Withdrawal shipping fee '.abs($this->_shipFee).'. Order:'.$this->_order['orders_code'];
		$options = array('cbhClass'=>0,	//正常扣款
							 'refCode'=>$this->_order['orders_code'],
							 'appType'=>3,	//物流费用
							 'cbhType'=>'-1',
							 'vale'=>$this->_shipFee,
							 'currencyCode'=>$this->_shipFeeCurrencyCode,
							 'note'=>$note
							);
		$ress = Customer_Service_CustomerBalance::procBalance($this->_customerId,$options);
		if(!$ress){
			$this->_error[] = 'Out of balance, please deposit you wms account.';
			$this->_outOfBalance = true;
			return false;
		}
		return true;
	 }
	 /**
	  * 检查订单重量是否符合
	  */
	 private function checkWeight(){
	     $lang = Zend_Registry::get('lang');
	 	$weight=Order_Service_Product::getOrderWeightByOrdercode($this->_orderCode);
	 	$orderproduct=Order_Service_Product::getByfield('orders_code', $this->_order['orders_code']);

	 	$arr_productid=array();
	 	if($orderproduct){
	 		foreach ($orderproduct as $val){
	 			$arr_productid[]=$val['product_id'];
	 		}
	 		
	 	}

	 	$pp_weight=new Product_Model_Product();
	 	$get_pp_weight=$pp_weight->getProductPackageWeightByProductId($arr_productid);
	 	
	 	if(!$get_pp_weight){
	 		$get_pp_weight=0;
	 	}
	 	
	 	if($this->_weight==0){
	 		
	 		$this->_error[] =$lang['must_integer'];
	 		return false;
	 	}
	 	
	 	if(abs($weight-$this->_weight)+$get_pp_weight>0.5){  //1000<>0.02
	 		$this->_error[] =$lang['weight_more_than_0_5_need_reason'];
	 		$this->_isWeight=false;
	 		return false;
	 	}
	 	
	 	return $this->_isWeight;
	 	
	 }
	 
	 
	 /**
	  * 修改订单状态
	  * 
	  */
	 private  function updateOrderStatus(){
	     $lang = Zend_Registry::get('lang');
	 	$date=date("Y-m-d:H:i:s");
	 	$row=array(
	 			'orders_status'=>5,
	 			'process_status'=>5,
	 			'last_modified_time'=>$date,
	 			'ship_date'=>$date,
	 			);
	 	$uos=Order_Service_Order::updateByOrdersCode($row,$this->_orderCode);
	 	
	 	
	 	if(!$uos){
	 		$this->_error[] =$lang['operation'].$lang['fail'];
	 		return false;
	 	}else{
	 		$this->_error[] =$lang['operation'].$lang['success'];
	 		return true;
	 	}
	 }

    /**
     * 绑定物流订单
     */
    public function boundOrder() {
        $lang = Zend_Registry::get('lang');
        $this->setCurrencyRate();//获取汇率
        $date=date("Y-m-d:H:i:s");
        //获取计费运费的计费重量
        if(isset($this->_shipType['real_weight']) && $this->_shipType['real_weight']>0 ){
            $real_weight = $this->_shipType['real_weight'];
        }else{
            $real_weight = 0; //出错时才为0
        }
        $date=date("Y-m-d H:i:s");
        $orderShipRow = array (
            "orders_code" => $this->_order['orders_code'],
            "warehouse_id" => $this->_order['warehouse_id'],
            "carrier_code" => 'WH',
            "tracking_number" =>$this->_tracking_number,
            "os_status" => 4 ,
            "os_declared_value" => $this->_order['parcel_declared_value'],
            "os_shipping_fee_estimate" => $this->_order['shipping_fee_estimate'],
            "os_create_date" => $date,
            'os_weight'=>$this->_weight,
            'os_width'=>$this->_width,
            'os_length'=>$this->_length,
            'os_height'=>$this->_height,
            'os_vol_weight'=>$real_weight,//体积重
            'os_shipping_fee'=>$this->_shipFee,
            'currency_rate'=>$this->_currency_rate,//当前币种汇率
            'os_last_update'=>$date
        );
        $model = new Order_Model_OrderShip();
        if (!$model->create($orderShipRow)){
            $this->_error[] =$lang['operation'].$lang['fail'];
            return false;
        }
        return true;
    }


	
    //订单历史
    public  function updateOrderHistory(){
        $lang = Zend_Registry::get('lang');
    	$date=date("Y-m-d:H:i:s");
    	$session = new Zend_Session_Namespace('userAuth');
    	$user_id=$session->userID;
    	
    	$addRow=array(
    			'orders_code'=>$this->_orderCode,
    			'osh_type'=>'Shipping',
    			'osh_statu'=>$this->_order['process_status'],
    			'osh_statu_now'=>5,
    			'osh_remark'=>'',
    			'osh_comments'=>"出货，总库存冻结数量被减",
    			'user_id'=>$user_id,
    			'osh_ip'=>Order_Service_History::getIP(),
    			'osh_create_date'=>$date,
    	);
    	$resultOH=Order_Service_History::create($addRow);
    	
    	if(!$resultOH){
    		$this->_error[] =$lang['operation'].$lang['fail'];
    		return false;
    	}
    	return $resultOH;
    
    }
	 
	 /**
	  * 修改库存冻结数
	  * 
	  */
	private  function updateQuantityHold(){
		$date=date("Y-m-d:H:i:s");
		$orders_shipment=$this->_orderCode;
        $session = new Zend_Session_Namespace('userAuth');
        $user_id=$session->userID;					//操作人
		
// 		订单产品
		$order_products = Order_Service_Product::getByfield("orders_code",$this->_orderCode);
		

		foreach($order_products as $val){
			$where = array('product_id'=>$val['product_id']);
			//默认仓库1 以后处理 待确认~~~~~~  注意注意-------------------------------------------------------
			$val['warehouse_id'] = 1;
			$productStocket = Product_Service_ProductStocket::getByProductId($val['product_id'],$val['warehouse_id']);
			
			//根据货架号/产品编号/客户编号，查出库存对应的记录行
			$quantity_hold=$productStocket['ps_quantity_hold'];

			if($quantity_hold<$val['op_quantity']){
				$this->_error[] ="产品ID[".$val['product_id']."]库存冻结数不可小于出货数!";
				return false;
			}
				
				
			if(!Product_Service_ProductStocket::updateQuantityHold($val['product_id'], $val['op_quantity'],$val['warehouse_id'],"Orders_Code：".$val['orders_code'])){
				$this->_error[] ="产品ID[".$val['product_id']."]库存冻结更新失败!";
				return false;
			}
			
			//如果总库存Hold数被减掉之前的数量等于要出货的数量
			if($productStocket['ps_quantity_hold']==$val['op_quantity']){
				//更改货架状态
				$wp_row=Warehouse_Service_Products::getByAllProductId($val['product_id']);
				foreach($wp_row as $wp){
					if($wp['wp_quantity_hold']==0&&$wp['wp_quantity']==0&&$wp['wp_status']==1){
						$row = array("wp_status"=>0);
						if(!Warehouse_Service_Products::update($row, $wp['wp_id'])){
							$this->_error[] ="货架状态更新失败!";
							return false;
						}else{
							//货架使用日志
							$WarehouseProductsLog = array(
									'wpl_refId' => $this->_orderCode,
									'user_id' => $user_id,
									'warehouse_id' => $val['warehouse_id'],
									'ws_code' => $wp['ws_code'],
									'wpl_proc_type' => 4, //状态修改
									'wpl_note' => '出货更改货架库存状态',
									'wpl_add_time'=>$date
							);
							if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
								$this->_error[] ='写入货架使用日志失败!wpl';
								return false;
							}
						}
					}
				}
			}		
		}
		
		return true;
		
	}
	 
}